package com.example.input

import java.io.{DataOutputStream, PrintWriter}
import java.net.{ServerSocket, Socket}

object SocketLikeNC {

  def main(args: Array[String]): Unit = {
    val port: Int = 9999
    val server = new ServerSocket(port)
    println(s"Socket Server 已启动： ${server.getInetAddress}:${server.getLocalPort}")
    while (true) {
      val socket: Socket = server.accept()
      println("成功连接到本地主机：" + socket.getInetAddress)
      new ServerThread(socket).start()
      Thread.sleep(100)
    }
  }

}

class ServerThread(sock: Socket) extends Thread {
  val words = "hello world hello spark hello word hello java hello hadoop hello kafka".split("\\s+")
  val length = words.length

  override def run(): Unit = {
    val out = new DataOutputStream(sock.getOutputStream)
    val random = scala.util.Random
    while (true) {
      val (wordx, wordy) = (words(random.nextInt(length)), words(random.nextInt(length)))
      out.writeUTF(s"$wordx $wordy")
      Thread.sleep(1000)
    }
  }
}
